package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合
 * @author qulq
 * @date 2024-07-07 13:33:24
 */
public class T77_Combinations{
	 public static void main(String[] args) {
	 	 //测试代码
	 	 Solution solution = new T77_Combinations().new Solution();
	 }
	 
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {

	List<List<Integer>> ans = new ArrayList<>();
	List<Integer> path = new ArrayList<>();

	public List<List<Integer>> combine(int n, int k) {
		ans.clear();
		backtracking(n, k, 1);
		return ans;
	}

	public void backtracking(int n, int k, int start) {
		if (path.size() == k) {
			ans.add(new ArrayList<>(path));
			return;
		}
		// 剪枝：1. 已经选择的元素个数：path.size();
		// 2. 还需要的元素个数为: k - path.size();
		// 3. 在集合n中⾄多要从该起始位置 : n - (k - path.size()) + 1，开始遍历
		for (int i = start; i <= n - (k - path.size()) + 1 ; i++) {
			path.add(i);
			backtracking(n, k, i + 1);
			path.remove(path.size() - 1);
		}
	}
}
//leetcode submit region end(Prohibit modification and deletion)

}